package chat

import (
	"fmt"
	"hft/Database/admin"
	"hft/Database/admin/user_db"
	"hft/Http/Services/chat/chat_model"
	"hft/Http/Services/new_clue/clue_utils"
	new_clue_lou_lou "hft/Http/Services/new_clue_lou"
	"hft/Http/Services/user/user_utils"
	"hft/global"
	"hft/tools"

	"gorm.io/gorm"
)

// 微聊线索
type Chat struct{}

/* 获取验证码 */
func (*Chat) LeaveChat(data *chat_model.ChatSearch, token string, ip string, port int, sid int) (err error) {
	err = global.OC_DB.Transaction(func(tx *gorm.DB) error {
		var lou *admin.LouPan
		var region *admin.Region
		var region_name string
		var louName string
		if data.LouID == 0 {
			global.OC_DB.First(&region, sid)
			region_name = region.Name
		} else {
			global.OC_DB.First(&lou, data.LouID)
			region_name = user_utils.GetBelongName(lou.BelongName)
			louName = lou.Name
		}
		var clue = &user_db.Clue{
			LouPanID:   data.LouID,
			Port:       port,
			OriginType: 2,
			IP:         ip,
			RegionName: region_name,
			LouName:    louName,
		}
		// 如果验证没通过则需要验证
		if _, ok := clue_utils.Jwt(token); !ok {
			// 查找该客户 如果该客户存在该微聊就不在新增微聊，如果不存在就新增该微聊 如果该客户不存在就创建
			var user *user_db.User
			if err = tx.Where("city = ? AND phone = ?", sid, data.Phone).First(&user).Error; err != nil {
				// 没有就创建一个客户并且生成一条线索
				uuid := tools.GenUUID2()
				var lou *admin.LouPan
				tx.Select("name, id, region_link").First(&lou, data.LouID)
				var regionLink string
				if data.LouID != 0 {
					regionLink = lou.RegionLink
				} else {
					var cityItem *admin.Region
					tx.First(&cityItem, sid)
					regionLink = fmt.Sprintf("%v%v,", cityItem.Link, cityItem.ID)
				}
				var newUser = &user_db.User{
					UUID:        uuid,
					Phone:       data.Phone,
					City:        sid,
					CityLink:    regionLink,
					IntendLouID: uint(data.LouID),
					Clues:       []*user_db.Clue{clue},
					IntendLou:   lou.Name,
					File:        0,
					Show:        0,
					Tag:         0,
				}
				tx.Create(&newUser)
			} else {
				// 如果存在该客户就修改客户的线索
				tx.Model(&user).Where("id = ?", user.ID).Updates(map[string]interface{}{
					"use_protect_times": user.UseProtectTimes + 1,
				})
				clue.UserID = user.ID
				tx.Create(&clue)
			}
			new_clue_lou_lou.SendValid(data.Phone)
			return nil
		}
		return nil
	})
	return err
}

var ChatService = new(Chat)
